package com.glsc.ngateway.platform.utils;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID;

/**
 * @Title: DocUtils
 * @Description: 文件类。
 * @author: 张宁
 * @version: 1.0.0
 * @date: 2020/12/21 16:29
 */
public class DocUtils {


    public static String saveFile(byte[] file, String filePath, String fileName) throws IOException {

        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath + fileName);
            FileChannel fileChannel = fileOutputStream.getChannel();
            ByteBuffer buf = ByteBuffer.wrap(file);
            while (fileChannel.write(buf) != 0) {
            }
        } catch (IOException e) {
            return "Exception";
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return filePath + fileName;
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    public static String tranformStyle(String source) throws UnsupportedEncodingException {
        char[] arr = source.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            char temp = arr[i];
            if (isChinese(temp)) {
                sb.append(URLEncoder.encode("" + temp, "UTF-8"));
                continue;
            }
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    public static String repalceSpecialWord(String url) throws UnsupportedEncodingException {
        url = url.replace(" ", "%20").replace("?", "%3F").replace("#", "%23")
                .replace("&", "%26").replace("=", "%3D").replace("+", "%2B");


        return url;
    }


    /**
     * 判断是不是中文字符
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;

    }


    /**
     * @param urlStr
     * @param savePath
     * @return
     * @throws IOException
     * @Description 通过URL下载附件
     */
    public static File downLoadFromUrl(String urlStr, String savePath) {

        try {
            String fileName = getFileNameFromUrl(urlStr);
            String resultUrl = tranformStyle(urlStr);
            resultUrl = repalceSpecialWord(resultUrl);
            URL httpurl = new URL(resultUrl);
            File f = new File(savePath + UUID.randomUUID() + "#" + fileName);
            FileUtils.copyURLToFile(httpurl, f);
            return f;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @param url
     * @return
     * @Description 通过URL获取附件文件名称
     */
    public static String getFileNameFromUrl(String url) {
        String name = new Long(System.currentTimeMillis()).toString() + ".X";
        int index = url.lastIndexOf("/");
        if (index > 0) {
            name = url.substring(index + 1);
            if (name.trim().length() > 0) {
                return name;
            }
        }
        return name;
    }


    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }


    public static String convertCharset(String s) {
        if (s != null) {
            try {
                int length = s.length();
                byte[] buffer = new byte[length];
                // 0x81 to Unicode 0x0081, 0x8d to 0x008d, 0x8f to 0x008f, 0x90
                // to 0x0090, and 0x9d to 0x009d.
                for (int i = 0; i < length; ++i) {
                    char c = s.charAt(i);
                    if (c == 0x0081) {
                        buffer[i] = (byte) 0x81;
                    } else if (c == 0x008d) {
                        buffer[i] = (byte) 0x8d;
                    } else if (c == 0x008f) {
                        buffer[i] = (byte) 0x8f;
                    } else if (c == 0x0090) {
                        buffer[i] = (byte) 0x90;
                    } else if (c == 0x009d) {
                        buffer[i] = (byte) 0x9d;
                    } else {
                        buffer[i] = Character.toString(c).getBytes("CP1252")[0];
                    }
                }
                String result = new String(buffer, "UTF-8");

                System.out.println(result);
                System.out.println(result);
                System.out.println(result);
                System.out.println(result);


                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
/*

        String url = "http://10.197.32.32:8080/filesystem/downDir/1607481204481632599/系统架构图-Page-5.jpg";
        File result = downLoadFromUrl(url, "D:/download_files/");
        List<File> finalList = new ArrayList<File>();
        finalList.add(result);
*/


        String s = "ÏµÍ³¹ÜÀíÔ±";


        System.out.println(getEncoding(s));

        String result = new String(s.getBytes("iso-8859-1"), "GBK");
        System.out.println("result:" + result);
        System.out.println("result:" + result);
        System.out.println("result:" + result);
        System.out.println("result:" + result);


        convertCharset(s);


    }

/*

    public static <T> List<T> linkedMapTypeListToObjectList(List<T> lst,Class<T> responseType){
        // 处理linkedHashMap
        lst = JSONObject.parseArray(JSONObject.toJSONString(lst)).toJavaList(responseType);
        return lst;
    }
*/


//    public static List linkedMapTypeListToObjectList(Object detailList, Class<Map> mapClass) {
//    }
}

